﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class PurchaseOrderDetailEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (Request.QueryString["PurchaseOrderID"] != null)
                {
                    if (mk.IsNumber(Request.QueryString["PurchaseOrderID"].ToString()))
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblPurchaseOrderID.Text = Request.QueryString["PurchaseOrderID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }

                //绑定页面基本数据
                this.BindData();

                ////设置经办人
                //UART.Accounts.Bus.User currentUser = (UART.Accounts.Bus.User)(Session["UserInfo"]);
                //this.lblCurrentUser.Text = currentUser.UserName;
                //this.lblManager.Text = currentUser.TrueName;
            }
        }
          private void BindMaterialCategoryID()
        {
           var bll = mk.l.Sales_MaterialCategory.ToList();
           var ds = bll.ToList();
            this.rbtnlMaterialCategoryID.DataSource = ds;
            this.rbtnlMaterialCategoryID.DataTextField = "Name";
            this.rbtnlMaterialCategoryID.DataValueField = "MaterialCategoryID";
            this.rbtnlMaterialCategoryID.DataBind();
        }

        /// <summary>
        /// Binds the manufacturer code.
        /// </summary>
        private void BindManufacturerCode()
        {
           var bll = mk.l.Sales_ManufacturerCode.ToList();
            var ds = bll.Where(h=>h.ManufacturerID.ToString()== this.lblManufacturerID.Text);
            this.rbtnlCode.DataSource = ds;
            this.rbtnlCode.DataTextField = "Code";
            this.rbtnlCode.DataValueField = "Code";
            this.rbtnlCode.DataBind();
        }

        /// <summary>
        /// Binds the data.绑定页面基本数据
        /// </summary>
        private void BindData()
        {
          var bll =mk.l.Sales_PurchaseOrderHeader.ToList();
           Sales_PurchaseOrderHeader m = bll.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
            if (m != null)
            {
                //先判断是否是本人添加的订单，不能修改别人添加的订单
               Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                //设置根部门ID
              var bllDept = mk.l.Accounts_Department.ToList();
                this.lblRootDepartmentID.Text = bllDept.Where(h=>h.ClassID==(int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();
                if (int.Parse(this.lblRootDepartmentID.Text) == m.RootDepartmentID)
                {
                    //显示厂家名称
                   var bllM = mk.l.Sales_Manufacturer.ToList();
Sales_Manufacturer mM = bllM.Where(h=>h.ManufacturerID==m.ManufacturerID).FirstOrDefault();
                    this.lblManufacturerName.Text = mM.ManufacturerName;
                    this.lblManufacturerID.Text = mM.ManufacturerID.ToString();
                    this.txtOrderNumber.Text = m.OrderNumber;
                    this.BindMaterialCategoryID();
                    this.BindManufacturerCode();
                    this.BindPurchaseOrderDetail();
                    //如果不是自己添加的订单 或者已经付款或已经到货 把编辑按钮设置为不显示
                    if (m.Manager != currentUser.UserName || m.StatusPayment == "1" || m.StatusArrival == "1")
                    {
                        this.pnlAdd.Visible = false;
                        this.btnOK.Enabled = false;
                        this.btnOK.Visible = false;
                        this.myGridView.Columns[4].Visible = false;
                        this.myGridView.Columns[5].Visible = false;
                    }
                }
                else
                {
                   mk.Alert("只能查看本店的订单！");
                }
            }
            else
            {
               mk.Alert("参数错误！此订货单不存在或已被删除");
            }
        }


        /// <summary>
        /// Binds the purchase order detail.
        /// </summary>
        private void BindPurchaseOrderDetail()
        {
          var bll = mk.l.Sales_MaterialandSales_PurchaseOrderDetail.ToList();
         var ds = bll.Where(h=>h.PurchaseOrderID.ToString()== this.lblPurchaseOrderID.Text);
            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
        }

        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
            var bll = mk.l.Sales_PurchaseOrderHeader.ToList();
Sales_PurchaseOrderHeader m = bll.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
                if (m != null)
                {
                    m.OrderNumber = mk.InputText(this.txtOrderNumber.Text, 30);
                    m.ModifiedDate = System.DateTime.Now;
                    try
                    {
                       // bll.Update(m);
                        mk.l.SubmitChanges();
                        //提交事务
                       // ContextUtil.SetComplete();
                       mk.Alert("订货单明细修改成功！");
                    }
                    catch (Exception ex)
                    {
                        //撤销事务
                      //  ContextUtil.SetAbort();
                       mk.Alert("订货单明细修改失败！错误信息：" + ex.Message);
                    }
                }
                else
                {
                   mk.Alert("订货单明细修改失败！此订货单不存在或已被删除");
                }
            }
        }

        /// <summary>
        /// Handles the RowDataBound event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblMaterialInventory = (Label)(e.Row.FindControl("lblMaterialInventory"));
               var bllInventory = mk.l.Sales_MaterialInventory.ToList();
                lblMaterialInventory.Text = bllInventory.Where(h=>h.MaterialID==int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["MaterialID"].ToString())).Sum(h=>h.Quantity).ToString();
            }
        }

        /// <summary>
        /// Handles the RowEditing event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.myGridView.EditIndex = e.NewEditIndex;
            this.BindPurchaseOrderDetail();
        }

        /// <summary>
        /// Handles the RowCancelingEdit event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.myGridView.EditIndex = -1;
            this.BindPurchaseOrderDetail();
        }

        /// <summary>
        /// Handles the RowUpdating event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (this.IsValid)
            {
               var bll = mk.l.Sales_PurchaseOrderDetail.ToList();
      Sales_PurchaseOrderDetail m = bll.Where(h=>h.DetailID==int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["DetailID"].ToString())).FirstOrDefault();
                if (m != null)
                {
                    TextBox txtQuantity = (TextBox)(this.myGridView.Rows[e.RowIndex].FindControl("txtQuantity"));
                    m.Quantity = decimal.Parse(txtQuantity.Text);
                    //bll.Update(m);
                    mk.l.SubmitChanges();
                }
                this.myGridView.EditIndex = -1;
                //重新绑定数据
                this.BindPurchaseOrderDetail();
            }
        }

        /// <summary>
        /// Handles the RowDeleting event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewDeleteEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            this.lblMsg2.Text = string.Empty;
     Sales_PurchaseOrderDetail bll =mk.l.Sales_PurchaseOrderDetail.ToList().Where(h=>h.DetailID==int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["DetailID"].ToString())).FirstOrDefault();
            try
            {
                mk.l.Sales_PurchaseOrderDetail.DeleteOnSubmit(bll);
                mk.l.SubmitChanges();
              //  bll.Delete(int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["DetailID"].ToString()));
                this.BindPurchaseOrderDetail();
                //提交事务
               // ContextUtil.SetComplete();
            }
            catch (Exception ex)
            {
                //撤销事务
             //   ContextUtil.SetAbort();
                this.lblMsg2.Text = "删除错误！错误信息：" + ex.Message;
            }
        }

        /// <summary>
        /// 添加订购材料
        /// </summary>
        protected void btnAddProduct_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                this.lblMsg2.Text = string.Empty;
                //实例化订购业务逻辑类和模型对象
             var bll = 
                   mk.l.Sales_PurchaseOrderDetail.ToList();
               Sales_PurchaseOrderDetail m = 
                new   Sales_PurchaseOrderDetail();
                try
                {
                    //先根据厂家代码取得厂家ID                   
                    int intMaterialID = 0;
                    //判断材料列表中有无此种材料 如果没有 则添加之
                    string strName = mk.InputText(this.txtName.Text, 50);
                    int intMaterialCategoryID = int.Parse(this.rbtnlMaterialCategoryID.SelectedValue);
                    int intManufacturerID = int.Parse(this.lblManufacturerID.Text);
                    //实例化材料业务逻辑类用来判断材料是否存在
                    var bllMaterial = mk.l.Sales_Material.ToList();
         Sales_Material mMaterial = new Sales_Material();
                    if (bllMaterial.Where(h=>h.MaterialCategoryID==intMaterialCategoryID & h.ManufacturerID== intManufacturerID & h.Name==strName).Count()==0)
                    {
                        //如果材料不存在于材料列表，则添加材料。
                        mMaterial.ManufacturerID = intManufacturerID;
                        mMaterial.MaterialCategoryID = intMaterialCategoryID;
                        mMaterial.Name = strName;
                        mMaterial.ManufacturerCode = this.rbtnlCode.SelectedValue;
                        mMaterial.RootDepartmentID = int.Parse(this.lblRootDepartmentID.Text);
                        mk.l.Sales_Material.InsertOnSubmit(mMaterial);
                        mk.l.SubmitChanges();
                        intMaterialID =mMaterial.MaterialID;
                    }
                    else
                    {
                        //如果材料存在，则获取材料编号
                        mMaterial = bllMaterial.Single(h=>h.MaterialCategoryID==intMaterialCategoryID & h.ManufacturerID== intManufacturerID & h.Name==strName);
                            
                        intMaterialID = mMaterial.MaterialID;
                    }
                    //为订货单明细实体属性赋值
                    m.ModifiedDate = System.DateTime.Now;
                    m.MaterialID = intMaterialID;
                    m.Quantity = decimal.Parse(this.txtQuantity.Text);
                    m.PurchaseOrderID = int.Parse(this.lblPurchaseOrderID.Text);
                    m.CostUnitPrice = 0;
                    m.Subtotal = 0;
                    m.StatusArrival = "0";
                    m.DateArrival = Convert.ToDateTime("9999-1-1");
                    //把入库仓库ID设置为0
                    m.InventoryManager = string.Empty;
                    m.LocationID = 0;
                    //向数据库中添加订货单明细
                   // bll.Add(m);
                    mk.l.Sales_PurchaseOrderDetail.InsertOnSubmit(m);
                    mk.l.SubmitChanges();
                    //绑定材料列表
                    this.BindPurchaseOrderDetail();
                    //把输入框设置为空
                    this.txtName.Text = string.Empty;
                    this.txtQuantity.Text = string.Empty;
                    //清除选定项
                    this.rbtnlMaterialCategoryID.ClearSelection();
                    //提交事务
                 //   ContextUtil.SetComplete();
                }
                catch (Exception ex)
                {
                    //撤销事务
                  //  ContextUtil.SetAbort();
                    this.lblMsg2.Text = "添加错误！错误信息：" + ex.Message;
                }
            }
        }

        /// <summary>
        /// Handles the ServerValidate event of the CustomValidator1 control.
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (this.myGridView.Rows.Count > 0)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }

        /// <summary>
        /// Handles the TextChanged event of the txtName control.输入材料货号后，查询材料表中有无此种材料，如有，自动显示厂家代码和材料类型
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void txtName_TextChanged(object sender, EventArgs e)
        {
            string strMaterialName = mk.InputText(this.txtName.Text, 50);
       var bll =mk.l.Sales_Material.ToList();
 Sales_Material m = bll.Where(h=>h.Name==strMaterialName).FirstOrDefault();
            if (m != null)
            {
                this.rbtnlMaterialCategoryID.Items.FindByValue(m.MaterialCategoryID.ToString()).Selected = true;
                //UART.BLL.Sales.Manufacturer bllM = new UART.BLL.Sales.Manufacturer();
                //UART.Model.Sales.Manufacturer mM = bllM.Where(h=>h.m.ManufacturerID);
                //if (mM != null)
                //{
                //    this.txtManufacturerCode.Text = mM.ManufacturerCode;
                //}
                this.rbtnlCode.Items.FindByValue(m.ManufacturerCode).Selected = true;
            }
            else
            {
                this.rbtnlMaterialCategoryID.ClearSelection();
                this.rbtnlCode.ClearSelection();
            }
        }

        /// <summary>
        /// Handles the ServerValidate event of the CustomValidator2 control.验证是否存在相同名称的材料
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
        {
          var bll = mk.l.Sales_Material.ToList();
         Sales_Material m = new Sales_Material();
            if (bll.Where(j=>j.MaterialCategoryID==int.Parse(this.rbtnlMaterialCategoryID.SelectedValue)&j.Name== mk.InputText(this.txtName.Text, 50)).Count()>0)
            {
                m = bll.Where(h=>h.MaterialCategoryID==int.Parse(this.rbtnlMaterialCategoryID.SelectedValue)&h.Name== mk.InputText(this.txtName.Text, 50)).FirstOrDefault();
                if (m.ManufacturerID != int.Parse(this.lblManufacturerID.Text))
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true;
                }
            }
            else
            {
                args.IsValid = true;
            }
        }

    }
}
